const { createService, removeService, updateService, findByIdService, findByPageService } = require('../services/projectService');
const AppError = require('../utils/AppError');
const Controller = require('../utils/Controller');
const { toi } = require('../utils/tools');

class ProjectController extends Controller {
	async create(req, res, next) {
		const schema = req.joi.object({
			name: req.joi.string().required(),
			url: req.joi.string(),
			github: req.joi.string(),
			description: req.joi.string(),
			thumb: req.joi.string(),
			order: req.joi.number()
		});
		const { error: failed } = schema.validate(req.body);
		if (failed) return next(new AppError(failed, 400));

		await toi(createService(req.body), res, next);
	}

	async remove(req, res, next) {
		await toi(removeService(req.params.id), res, next);
	}

	async update(req, res, next) {
		const schema = req.joi
			.object({
				name: req.joi.string(),
				url: req.joi.string(),
				github: req.joi.string(),
				description: req.joi.string(),
				thumb: req.joi.string(),
				order: req.joi.number()
			})
			.unknown(true);
		const { error: failed } = schema.validate(req.body);
		if (failed) return next(new AppError(failed, 400));

		await toi(updateService(req.body, req.params.id), res, next);
	}

	// 查全部
	async findByPage(req, res, next) {
		await toi(findByPageService(req.query), res, next);
	}

	// 查单个
	async findById(req, res, next) {
		await toi(findByIdService(req.params.id), res, next);
	}
}

module.exports = new ProjectController();
